package net.rock.eshop.controller;

import net.rock.eshop.entity.User;
import net.rock.eshop.exception.UnauthorizedOperationException;
import net.rock.eshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/account")
public class AccountController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(@RequestBody User user){
        Optional<String> res = userService.login(user.getUsername(),user.getPassword(),user.getPermission());
        return res.orElseThrow(UnauthorizedOperationException::new);
    }

    @GetMapping ("/logout")
    public void logout(@CookieValue(value = "sessionID", defaultValue = "") String sessionId) {
        if (sessionId.isEmpty()) {
            throw new UnauthorizedOperationException();
        }
        userService.logout(sessionId);
    }

    @PostMapping("/reg")
    public void reg(@RequestBody User user){
        userService.register(user);
    }
}
